<?php
class Authentification{
	private $db, $table;
	private $user, $passwd, $id, $mail, $domain;
	private $key, $keyTable;


	function __construct($db, $table, $keyTable){
		Session::start();
		$this->db = $db;
		$this->table = $table;
		$this->keyTable = $keyTable;
		$this->log = new Logger("Auth\t", _LOGPATH_);
		$this->log->setLogLevel(Logger::VERBOSE);
	}

	public function create($user, $passwd, $group, $mail, $domain){
		$this->db->insert("INSERT INTO user (user, passwd, usergroup, mail, domain) VALUES ('%s', '%s', '%s', '%s', '%s')",
		$user, md5(_SALT_.$passwd), $group, $mail, $domain
		);
	}

	public function verify($id, $key){
		$this->id = $id;
		$this->key= $key;
		$this->log->debug("Trying to verify with $id, $key");
		$selection = $this->db->select("SELECT user FROM $this->keyTable WHERE user=%d AND `key`='%s'",$this->id, $this->key);
		$numOfRows = $selection->getRowNum();
		if($numOfRows == 1){
			return true;
		}else{
			return false;
		}
	}

	public function login($user, $passwd){
		$this->log->debug("Trying to login with $user, $passwd");
		$this->user = $user;
		$this->passwd = $passwd;
		$selection = $this->db->select("SELECT id FROM $this->table WHERE user='%s' AND pwd='%s'",$this->user, crypt($this->passwd, _SALT_));
		$numOfRows = $selection->getRowNum();
		if($numOfRows == 1){
			$result = $selection->getRow();
			$this->id = $result[0];
			$this->createKey();
			Session::set("id",$this->id);
			Session::set("key",$this->key);
			$this->log->verbose("Login successful");
			return true;
		}else{
			return false;
			$this->log->warning("Login failed!");
		}
	}

	private function createKey(){
		$this->key = Util::getUniqueKey();
		$this->db->insert("INSERT INTO $this->keyTable VALUES('%s', '%s', '%s')",$this->key,$this->id,  null);
	}


	public function sendRequest($id, $key, $data){
		if($key == $this->key){
			return "XX-".$data;
		}else{
			return 401;
		}
		return true;
	}

	public function logout(){
		session_unset();
		session_destroy();
	}

	public function getUser(){
		return $this->user;
	}

	public function getId(){
		return $this->id;
	}

	public function getKey(){
		return $this->key;
	}
}